import Vuex from 'vuex'
import Vue from 'vue'
import {userLogin} from '@/api/userApi'
import {shiroLogin} from '@/api/userApi-shiro'

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    version: '1.0.0',
    isLogin: false,
    token: '',
    userLocation: { // 用户信息
      longitude: null, // 经度
      latitude: null, // 纬度
      locationCity: '' // 定位城市
    },
    userInfo: {
      token: '',
      refreshToken: '',
      userId: '',
      username: '',
      deptId: '',
      tenantId: '',
      avatar: ''
    }
  },
  mutations: {
    SET_USER_INFO: (state, info) => {
      state.userInfo.token = info.access_token;
      state.userInfo.refreshToken = info.refresh_token;
      state.userInfo.userId = info.user_id;
      state.userInfo.username = info.username;
      state.userInfo.avatar = info.avatar;
      state.userInfo.deptId = info.dept_id;
      state.userInfo.tenantId = info.tenant_id;
      state.isLogin = true;
    },
    LOGIN_OUT(state) {
      state.isLogin = false;
      state.userInfo.token = '';
      state.userInfo.refreshToken = '';
      state.userInfo.userId = '';
      state.userInfo.username = '';
      state.userInfo.avatar = '';
      state.userInfo.deptId = '';
      state.userInfo.tenantId = '';
      state.isLogin = false;
    },
    SET_TOKEN(state, token) {
      state.token = token;
    }
  },
  actions: {
    storeLogin({commit}, userData) {
      return new Promise((resolve, reject) => {
        userLogin(userData).then(response => {
          commit('SET_USER_INFO', response)
          uni.setStorageSync('token', response.access_token)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    shiroLogin({commit}, userData) {
      return new Promise((resolve, reject) => {
        shiroLogin(userData).then(response => {
          uni.setStorageSync('token', response.data.token)
          commit('SET_TOKEN', response.data.token)
          resolve(response)
        }).catch(error => {
          // this.tui.toast("用户名或密码错误", 2000, false)
          reject(error)
        })
      })
    },
    storeLogout({commit}) {
      return new Promise((resolve, reject) => {
        commit('LOGIN_OUT')
        uni.clearStorage()
        resolve()
      })
    }
  }
});

export default store
